enum BrowseType { officialContent, video, ceramic }

class BrowseRecord {
  final int? id;
  final int userId;
  final int contentId;
  final BrowseType type;
  final DateTime browseTime;

  BrowseRecord({
    this.id,
    required this.userId,
    required this.contentId,
    required this.type,
    required this.browseTime,
  });

  // 从JSON构造
  factory BrowseRecord.fromJson(Map<String, dynamic> json) {
    return BrowseRecord(
      id: json['id'],
      userId: json['user_id'],
      contentId: json['content_id'],
      type: BrowseType.values[json['type'] ?? 0],
      browseTime: _parseDateTime(json['browse_time']),
    );
  }

  // 解析日期时间
  static DateTime _parseDateTime(dynamic value) {
    if (value == null) {
      return DateTime.now();
    } else if (value is int) {
      return DateTime.fromMillisecondsSinceEpoch(value);
    } else if (value is String) {
      return DateTime.parse(value);
    }
    return DateTime.now();
  }

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      if (id != null) 'id': id,
      'user_id': userId,
      'content_id': contentId,
      'type': type.index,
      'browse_time': browseTime.millisecondsSinceEpoch,
    };
  }

  // 创建副本但修改部分属性
  BrowseRecord copyWith({
    int? id,
    int? userId,
    int? contentId,
    BrowseType? type,
    DateTime? browseTime,
  }) {
    return BrowseRecord(
      id: id ?? this.id,
      userId: userId ?? this.userId,
      contentId: contentId ?? this.contentId,
      type: type ?? this.type,
      browseTime: browseTime ?? this.browseTime,
    );
  }
}
